package service

import (
	"cgs-server/server/cgs/app/models"
	"cgs-server/server/cgs/app/models/dto"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
)

type WorksheetShortCutSrv interface {
	Detail(user *model.User, id string) (interface{}, error)
	Delete(groupId string, newGroupId string, linkType string, user *model.User) error
	Save(wg *models.WorksheetShortCut, user *model.User) error
	Update(wg *dto.WorksheetShortCut, user *model.User) error
}

type worksheetShortCutSrv struct {
	store store.Factory
}

func (w *worksheetShortCutSrv) Update(wg *dto.WorksheetShortCut, user *model.User) error {
	// 处理worksheetInfoIds
	return nil
}

func (w *worksheetShortCutSrv) Save(wg *models.WorksheetShortCut, user *model.User) error {
	err := w.store.WorksheetSortCut().Save(wg, user, v1.CreateOptions{})
	if err != nil {
		return err
	}

	// 更新 app 中的分组顺序
	if err != nil {
		return err
	}
	if err != nil {
		return err
	}

	return nil
}

func (w *worksheetShortCutSrv) Delete(sheetId string, url string, linkType string, user *model.User) error {

	arr := bson.A{
		bson.M{"sheetId": sheetId},
	}
	if url != "" {
		arr = append(arr, bson.M{"url": url})
	}
	if linkType != "" {
		arr = append(arr, bson.M{"linkType": linkType})
	}
	filter := bson.M{
		"$and": arr,
	}
	err := w.store.WorksheetSortCut().Delete(&models.WorksheetShortCut{}, user, filter)
	return err
}

func (w *worksheetShortCutSrv) Detail(user *model.User, id string) (interface{}, error) {
	listOptions := v1.ListOptions{}
	if id != "" {
		filter := bson.M{
			"sheetId": id,
		}
		listOptions.SetFilter(&filter)
	}
	wg := &models.WorksheetShortCut{}
	result, err := w.store.WorksheetSortCut().List(wg, user, listOptions)

	return result, err
}

func newWorksheetShortCutSrv(s *service) WorksheetShortCutSrv {
	return &worksheetShortCutSrv{
		store: s.store,
	}
}
